'use strict';

define([
    'controllers',
    '../service/adminService'
], function (controllers) {
    controllers.system.register('AdminController', ['$scope', '$q', 'AdminService', function ($scope, $q, adminService) {
        $scope.init = function () {
            $scope.pageNo = 1;
            $scope.pageSize = 10;
            $scope.initEditForm();
        };

        $scope.initEvent = function () {
            $('#editDialog').on('shown.bs.modal', function (e) {
                $('#save_account').focus();
            });
            $('#save_account').keypress(function (e) {
                if (isSubmitKeyCode(e)) {
                    $scope.save();
                }
            });
            $('#save_account').keyup(function (e) {
                if (!isSubmitKeyCode(e)) {
                    if ($scope.save_account != null) {
                        $scope.save_account = $scope.save_account.toUpperCase();
                        adminService.getLdapUser({account: $scope.save_account}, function (ldapUser) {
                            if (ldapUser.id != null) {
                                $scope.save_name = ldapUser.name;
                                $scope.save_email = ldapUser.email;
                            } else {
                                $scope.save_name = '';
                                $scope.save_email = '';
                            }
                        });
                    } else {
                        $scope.save_name = '';
                        $scope.save_email = '';
                    }
                }
            });
        };
        $scope.initEditForm = function () {
            $scope.save_account = '';
            $scope.save_name = '';
            $scope.save_email = '';
        };

        $scope.query = function (pageNo) {
            if (pageNo != null) {
                $scope.pageNo = pageNo;
            }
            $scope.paged = adminService.query({
                account: $scope.query_account,
                name: $scope.query_name,
                pageNo: $scope.pageNo,
                pageSize: $scope.pageSize
            });
        };
        $scope.save = function () {
            if (isEmpty($scope.save_account)) {
                $('#editErrorMsg').html('账号不能为空').removeClass('hide');
                $('#save_account_group').addClass('has-error');
                $scope.save_name = "";
                $scope.save_email = "";
                return;
            }
            $scope.validAccount(function () {
                adminService.save({}, {
                    account: $scope.save_account
                }, function () {
                    $scope.query();
                    $scope.initEditForm();
                    $('#editDialog').modal('hide');
                });
            });
        };

        $scope.setSelectId = function (id) {
            $scope.selectId = id;
        };
        $scope.getSelectIds = function () {
            var selectIds = new Array();
            $('input[name="id"]:checked').each(function () {
                selectIds.push($(this).val());
            });
            return selectIds;
        };
        $scope.toggleAllChk = function () {
            if (!$scope.chk_all) {
                $('input[name="id"]').prop('checked', true);
            } else {
                $('input[name="id"]').prop('checked', false);
            }
        };

        $scope.remove = function () {
            adminService.remove({id: $scope.selectId}, function () {
                $scope.query();
                $('#removeDialog').modal('hide');
            });
        };
        $scope.openRemoveAllDialog = function () {
            var ids = $scope.getSelectIds();
            if (ids == null || ids.length == 0) {
                return;
            }
            $('#removeAllDialog').modal('show');
        };
        $scope.removeAll = function () {
            var ids = $scope.getSelectIds();
            adminService.removeAll({ids: ids}, function () {
                $scope.query();
                $('#removeAllDialog').modal('hide');
                $scope.chk_all = false;
            });
        };
        $scope.disable = function () {
            adminService.disable({id: $scope.selectId}, function () {
                $scope.query();
                $('#disableDialog').modal('hide');
            });
        };
        $scope.openDisableAllDialog = function () {
            var ids = $scope.getSelectIds();
            if (ids == null || ids.length == 0) {
                return;
            }
            $('#disableAllDialog').modal('show');
        };
        $scope.disableAll = function () {
            var ids = $scope.getSelectIds();
            adminService.disableAll({ids: ids}, function () {
                $scope.query();
                $('#disableAllDialog').modal('hide');
                $scope.chk_all = false;
            });
        };
        $scope.enable = function (id) {
            adminService.enable({id: id}, function () {
                $scope.query();
            });
        };
        $scope.validAccount = function (callback) {
            $('#save_account_group').removeClass('has-error');
            $('#editErrorMsg').addClass('hide');

            if (isEmpty($scope.save_account)) {
                return;
            }

            var exist = function () {
                var defered = $q.defer();
                adminService.getByAccount({account: $scope.save_account}, function (data) {
                    if (data.id == null) {
                        defered.resolve('ok');
                    } else {
                        defered.reject('账号已存在，请重新输入');
                    }
                });
                return defered.promise;
            };

            var getLdapUser = function () {
                var defered = $q.defer();
                adminService.getLdapUser({account: $scope.save_account}, function (ldapUser) {
                    if (ldapUser.id != null) {
                        defered.resolve(ldapUser);
                    } else {
                        defered.reject('LDAP中不存在此账号');
                    }
                });
                return defered.promise;
            };

            var promise = exist();
            promise.then(getLdapUser)
                .then(function (ldapUser) {
                    $scope.save_name = ldapUser.name;
                    $scope.save_email = ldapUser.email;

                    if (callback != null) {
                        callback();
                    }
                }, function (err) {
                    $('#editErrorMsg').html(err).removeClass('hide');
                    $('#save_account_group').addClass('has-error');
                    $scope.save_name = "";
                    $scope.save_email = "";
                });
        };

        $scope.toggleCollectionRoleMap = {};
        $scope.openPrivilegeDialog = function (admin) {
            $scope.toggleCollectionRoleMap = {};
            $scope.privilegeAdminId = admin.id;
            adminService.getPrivilege({id: $scope.privilegeAdminId}, function (data) {
                $scope.adminRoles = data.adminRoles;
                $scope.adminCollections = data.adminCollections;
                $scope.roles = data.roles;
                $scope.collections = data.collections;

                $scope.roleMap = {};
                $scope.collectionMap = {};
                for (var i = 0 ; i < $scope.roles.length; i++) {
                    $scope.roleMap[$scope.roles[i].id] = $scope.roles[i];
                }
                for (var i = 0; i < $scope.collections.length; i++) {
                    $scope.collectionMap[$scope.collections[i].id] = $scope.collections[i];
                }
                for (var i = 0; i < $scope.roles.length; i++) {
                    if ($scope.adminCollections[$scope.roles[i].id] == null) {
                        $scope.adminCollections[$scope.roles[i].id] = {};
                    }
                }
            });
            $('#privilegeDialog').modal('show')
        };

        $scope.savePrivilege = function () {
            adminService.savePrivilege({
                id: $scope.privilegeAdminId
            }, {
                roles : $scope.adminRoles,
                collectionRoles: $scope.adminCollections
            }, function () {
                $('#privilegeDialog').modal('hide')
            });
        };

        $scope.toggleCollectionRole = function(roleId) {
            for (var i = 0; i < $scope.collections.length; i++) {
                $scope.adminCollections[roleId][$scope.collections[i].id] = !$scope.toggleCollectionRoleMap[roleId];
            }
        };

        $scope.init();
        $scope.initEvent();
        $scope.query();
    }]);
});